package com.qust.enDecrpytion.proxy.status;

import com.qust.enDecrpytion.proxy.StatusHandleFunction;
import lombok.NoArgsConstructor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
@NoArgsConstructor
public class PoJoTypeHandle extends AbstractTypeHandle {

    @Override
    public <T> T handle(T target,boolean cache ,Class<? extends Annotation> annotation, StatusHandleFunction function) throws Exception {
        if (!target.getClass().isPrimitive()) {
            Field[] fields = target.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(annotation) && field.getType() == String.class) {
                    field.setAccessible(true);
                    String LruKey = (String) field.get(target);
                    String value;
                    if (cache){
                        if ((value = getFromCache(LruKey, annotation)) != null) {
                            field.set(target, value);
                        } else {
                            String temp = function.enDecryption(LruKey);
                            add2Cache(LruKey, temp, annotation);
                            field.set(target, temp);
                        }
                    }else {
                        String temp = function.enDecryption(LruKey);
                        field.set(target, temp);
                    }
                }
            }
            return target;
        } else {
            return null;
        }
    }
}
